;layui.define(['layer','jquery','laytpl','table','laydate','form','element','laypage'],function (exports) {
    "use strict";
    let layer = layui.layer
    , $ = layui.jquery
    , laytpl = layui.laytpl
    , table = layui.table
    , laydate = layui.laydate
    , form = layui.form
    , element = layui.element
    , laypage = layui.laypage
    , deps = {
        'layer':layer
        ,'$':$
        ,'laytpl':laytpl
        ,'table':table
        ,'laydate':laydate
        ,'form':form
        ,'element':element
        ,'laypage':laypage
    }
    , MOD_NAME = 'common'
    , Common = function(){
        this.subEvents = {}
        this.tablesOption = {};
        this.renderDOMElOption = {}
    }
    Common.prototype = {
        constructor:Common
        ,deps:deps
        //伪数组转为真数值
        , arrayLike(arrLike){
            return Array.from ? Array.from(arrLike) : Array.prototype.slice.call(arrLike);
        }
        //元素相对屏幕偏移量，不需要兼容ie8以下
        , offset(el){
            let rect = el.getBoundingClientRect()
                ,sl = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft)
                ,st = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
            return {
                l: rect.left + sl,
                t: rect.top + st,
                w: el.offsetWidth,
                h: el.offsetHeight
            };
        }
        //获取相同类名元素
        , getCls(oParent,className){
            typeof oParent == 'string' && (
                className = oParent,
                    oParent = null
            )
            oParent = oParent ? oParent : document;
            let classEls = []
                , els = oParent.getElementsByTagName('*')
                , oElsLen = els.length;
            for(let i = 0; i < oElsLen; i++){
                if(els[i].className == className){
                    classEls.push(els[i]);
                }
            }
            return classEls;
        }
        /**
        * 根据属性值获取元素
        * pSelector: 父容器
        * selector：目标选择器
        * attrs: {moutel:'.hztree',index:'1'}
        * */
        , getElByAttrs(pSelector,selector,attrs){
            if(typeof selector == 'object'){
                attrs = selector
                selector = pSelector
                pSelector = null
            }
            let targetEls = []
                , els = this.query(pSelector,selector)
            if(els){
                let attrNames = Object.keys(attrs)
                    , attrNamesLen = attrNames.length
                    //是否符合条件
                    , isAccord = function(){
                        let isFlag = true;
                        for(let i = 0; i < attrNamesLen; i++){
                            if(els.getAttribute(attrNames[i]) != attrs[attrName]){
                                isFlag = false;
                                break;
                            }
                        }
                        return isFlag;
                    }
                //id选择器获取的元素本身，而非一个伪数组
                if(!els.length){
                    let isFlag = isAccord();
                    isFlag && targetEls.push(els)
                }else{
                    this.arrayLike(els).forEach(el=>{
                        let isFlag = isAccord();
                        isFlag && targetEls.push(el)
                    })
                }
            }
            return targetEls;
        }
        , isDOMEl:typeof HTMLElement === 'object'
            ? function(obj) {return obj instanceof HTMLElement;}
            : function(obj) {return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';}
        , queryAll(oParent,selector){
            if(typeof oParent == 'string'){
                selector = oParent
                oParent = null;
            }
            return  !oParent ? oParent.querySelectorAll(selector) : document.querySelectorAll(selector)
        }
        , getEl(selector){
            if(this.isDOMEl(selector)){
                return selector;
            }else{
                return document.getElementById(selector);
            }
        }
        , css(el,cssAttr,val,unit=''){
            //获取属性值
            if(!val && typeof cssAttr == 'string'){
                return el.currentStyle ? el.currentStyle[cssAttr] : document.defaultView.getComputedStyle(el,false)[cssAttr];
            }
            let setUnit = function (val) {
                //如果只是数字或小数
                if(/^(\d?.)?(\d+)?$/.test(val)){
                    unit = 'px'
                }
            }
            //以对象的方式传值
            if(!val && this.isPlainObject(cssAttr)){
                for(let cssKey in cssAttr){
                    val = cssAttr[cssKey]
                    setUnit(val)
                    el.style.cssText += ';' +(cssKey + ':' + val+unit)
                }
            }else{
                setUnit(val)
                el.style.cssText += ';' +(cssAttr + ':' + val+unit)
            }
        }
        , append(targetEl,html){
            if(typeof html == 'string'){
                //创建html片段流，fragment存放在内存中
                //将节点全部先追加到html片段流中，最后将html片段流一次性追加至html文档中
                //而不是一个一个节点的追加到html文档中
                let fragment = document.createDocumentFragment();
                let tempEl = document.createElement('div');
                tempEl.innerHTML = html;
                let appendEls = [];
                //firstElementChild只包含元素节点本身
                //firstChild,包含 元素节点+文本节点+注解
                while (tempEl.firstElementChild){
                    appendEls.push(tempEl.firstElementChild)
                    fragment.appendChild(tempEl.firstElementChild)
                }
                targetEl.appendChild(fragment);
                return appendEls
            }else{
                return targetEl.appendChild(html);
            }
        }
        , insertAfter(newNode,targetNode){
            let parent = targetNode.parentNode;
            if(parent.lastChild == targetNode){
                //向指定父容器中追加子元素
                parent.appendChild(newNode)
            }else{
                //containerEl.innserBefore(newNode,targetNode)
                //在指定父容器中，将newNode追加至targetNode之前
                parent.innserBefore(newNode,targetNode.nextSibling);
            }
        }
        , closest(el, selector){
            if(!this.isDOMEl(el)){return;}
            let els, targetEl
                ,isSame = (els, el)=>{
                let len = els.length;
                for(let i = 0; i<len; i++){
                    if(els[i].isSameNode(el)){
                        return els[i];
                    }
                }
                return false;
            }
                ,traversal = (el, selector)=>{
                els = this.queryAll(el.parentNode, selector);
                targetEl = isSame(els, el);
                while(!targetEl){
                    el = el.parentNode;
                    //判断节点是否是html根节点
                    if(el && el.nodeType == el.DOCUMENT_NODE){
                        return false;
                    }
                    traversal(el, selector);
                }
                return targetEl;
            };
            return traversal(el, selector);
        }
        , arrayConcact(){
            let otherArrays = this.arrayLike(arguments)
            ,targetArray = otherArrays.shift()
            ,otherArraysLen = otherArrays.length;
            for(let i=0; i<otherArraysLen; i++){
                try {//ES6
                    targetArray = targetArray.push(...otherArrays[i]);
                }catch(err){
                    targetArray = targetArray.concat(otherArrays[i]);
                }
            }
        }
        , delEleInArray(arr,val){
            return arr.splice(arr.indexOf(val),1);
        }
        , isHasPro(obj,pro){
            return obj.hasOwnProperty(pro);
        }
        , reverseStr(str){
            return str.trim().replace(/\s+/g,' ').split(' ').reverse().join('');
        }
        //判断客户端类型
        ,os(){
            let ua = navigator.userAgent,
                isWindowsPhone = /(?:Windows Phone)/.test(ua),			//手机版window
                isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone, //塞班
                isAndroid = /(?:Android)/.test(ua),				//安卓
                isIos = /\(i[^;]+;( U;)? CPU.+Mac OS X/.test(ua), 	//ios
                isIE = /(?:MSIE)/.test(ua),				//IE
                isFireFox = /(?:Firefox)/.test(ua),		//火狐
                isChrome = /(?:Chrome|CriOS)/.test(ua),	//Chrome
                isPresto = /(?:Presto)/.test(ua),		//opera内核
                isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)), //平板
                isIphone = /(?:iPhone)/.test(ua) && !isTablet,	//iPhone
                isPc = !isIphone && !isAndroid && !isSymbian && !isTablet && !isWindowsPhone, //pc
                isMobile = /AppleWebKit.*Mobile.*/.test(ua);
            return {
                isTablet: isTablet,
                isIphone: isIphone,
                isIos:isIos,
                isIE:isIE,
                isAndroid : isAndroid,
                isChrome: isChrome,
                isMobile:isMobile,
                isPc: isPc
            };
        }
        //获取IE版本
        ,IEV(){
            return navigator.userAgent.match(/(?:MSIE\s+(\d)+\.\d)/)[1];
        }
        ,headWordToUpCase(str){
            return str.toLowerCase().replace(/\b(\w)|\s(\w)/g,function(word){return word.toUpperCase()})
        }
        /**
         * 判断数据类型
         * var isFunction = isType('function')
         * isFunction(obj)
        */
        , isType(type){
            return (obj)=>{
                type = this.headWordToUpCase(type);
                return Object.prototype.toString.call(obj) == `[object ${type}]`;
            }
        }
        //日期处理
        ,date:{
            //小于10补零
            addZero:function(num){
                return num > 9 ? num : "0"+num;
            }
            //格式化时间
            ,formatDate:function(date,separate){
                if(!typeof separate == 'string' && separate != undefined){
                    throw new Error("separate "+separate+" is not string type");
                }
                var separate = separate || '-';
                return date.getFullYear() + separate
                    + this.addZero(date.getMonth() + 1)+ separate
                    + this.addZero(date.getDate())+" "
                    + this.addZero(date.getHours())+":"
                    + this.addZero(date.getMinutes())+":"
                    + this.addZero(date.getSeconds());
            }
            //获取date
            ,getDate:function(dateStr){
                //日期格式yyyy-MM-dd
                let regDate = /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/
                if(regDate.test(dateStr)){
                    let dateArr = dateStr.split("-")
                    return new Date(dateArr[0],dateArr[1],dateArr[2],0,0,0)
                }
                return new Date(dateStr);
            }
            //获取时间戳
            ,getTimeStamp:function(date){
                return date.getTime();
            }
            //计算时间差
            ,timeDiffer:function(beginDateStr,endDateStr){
                var startTime = new Date(beginDateStr);
                var endTime = new Date(endDateStr);
                var date3= endTime.getTime() - startTime.getTime();
                var days = Math.floor(date3/(24*3600*1000));
                return days;
            }
            //计算时间差,当beginDateStr,endDateStr相同时，包含这天
            ,timeDifferInclude:function(beginDateStr,endDateStr){
                var startTime = new Date(beginDateStr);
                var endTime = new Date(endDateStr);
                var date3= endTime.getTime() - startTime.getTime();
                var days = Math.floor(date3/(24*3600*1000))+1;
                return days;
            }
            /**
             * set多少天前/后的date
             * date：可以是（时间戳，格式化时间YYYY-MM-dd HH:mm:ss字符串，Date对象）
             */
            ,setManyDays:function(date,manyDays){
                date = new Date(date)
                date.setDate(date.getDate() + (manyDays));
                return date;
            }
            //获取指定年、月的天数
            ,getDays:function(year, month){
                month = parseInt(month,10);
                var d= new Date(year,month,0);
                return d.getDate()
            }
            /**
             * 计时器
             * 参数：num 毫秒数
             */
            /* 例1：convertTime(10*1000)//10秒
             * 例2：convertTime(28*60*1000)//28分钟
             * 例3：convertTime(2*3600*1000)//2个小时
             * 例4：convertTime(2*60*60*1000+28*60*1000+10*1000)//2小时 28分钟 10秒
             * 例5：convertTime(2*3600*1000+3600*1000+60*1000)//3小时 1分钟 0秒
            */
            ,timer:function(num){
                num = parseInt(num/1000);
                var second = num%60
                    ,minute = parseInt(num/60)%60
                    ,hour = parseInt(num/3600);
                return this.addZero(hour)+":"+this.addZero(minute)+":"+this.addZero(second);
            }
            ,getLenTime:function(lenTime,unit){
                //时间单位
                //皮秒，纳秒，微妙，毫秒，秒，分钟，小时，天，月，年
                let units = ['ps','ns','μs','ms','s','m','h','d','m','y']
                //默认时间单位：秒
                unit = unit || 's'
                let index = units.indexOf(unit);
                let baseVal = (units.length - index)
                if(index > 3){

                }
            }
        }
        //动画结束后的回调
        ,animationEnd(ele,sucHandle,errHandle){
            //1、获取动画名
            let animateName = function(){
                let animation = {
                    'animation': 'animationend',
                    'OAnimation': 'oAnimationEnd',
                    'MozAnimation': 'mozAnimationEnd',
                    'WebkitAnimation': 'webkitAnimationEnd'
                }
                let animateName = (function(el) {
                    for (let t in animation) {
                        if (el.style[t] !== undefined) {
                            return animation[t];
                        }
                    }
                })(document.createElement('div'));
                return animateName;
            }();
            //2、给ele绑定动画结束的回调
            let animateEndEventListener = function(aniEndHandle){
                let called = false ;
                //在每次transitionEnd的事件后执行该函数
                let callback = function(e,ele){
                    if (!called){
                        called=true;
                        aniEndHandle.call(this,e,ele);
                    }
                };
                ele.addEventListener(animateName,function(e){
                    callback.call(this,e,ele);
                    //通过setTimeout来补救windowphone中不触发事件的问题
                    setTimeout(callback,100);
                },false);
            }
            animateName ? animateEndEventListener(sucHandle):errHandle(ele);
        }
        ,getQueryStr:function(pattern){
            let argStr = pattern=='hash' ? location.hash.substring(1) : /.+\?(.+)$/.exec(location.href)[1]
                ,argArr = argStr.split('&')
                ,params = {};
            argArr.forEach(param => {
                if (/=/.test(param)) { // 处理有 value 的参数
                    let [key, val] = param.split('='); // 分割 key 和 value
                    val = decodeURIComponent(val); // 解码 //加密：encodeURIComponent()
                    val = /^\d+$/.test(val) ? parseFloat(val) : val; // 判断是否转为数字
                    if (params.hasOwnProperty(key)) {
                        params[key] = [].concat(params[key], val);
                    } else {
                        params[key] = val;
                    }
                }
            });
            return params;
        }
        //提示消息
        , msg:{
            //消息
            info(message){
                layer.msg(message,function(){})
            }
            //警告
            ,warn(message,end){
                return layer.msg(message,{icon:0,end:function(){
                   typeof end == 'function' && end.call(this)
                }})
            }
            //正确
            ,success(message,end){
                layer.msg(message,{icon:1,end:function(){
                     typeof end == 'function' && end.call(this)
                }})
            }
            //错误
            ,error(message,end){
                layer.msg(message,{icon:2,end:function(){
                        typeof end == 'function' && end.call(this)
                }})
            }
            //询问
            ,confirm(message,ensure,cancle){
                layer.confirm(message,{icon:3},function (index) {
                    typeof ensure == 'function' && ensure.call(this,index);
                },function(index){
                    if(!cancle){
                        common.closeLayer(index);
                        return
                    }
                    typeof cancle == 'function' && cancle.call(this,index);
                })
            }
            //加载层,返回load加载层索引
            ,load(options){
                return layer.load(0, $.extend({}, {
                    time:0 //可以设置你想要得时间
                    ,shade:0.4
                    ,success:function(layero,index){}
                    ,end(){}
                },options))
            }
            //吸附层提示类型
            ,tips(options){
                let direct = {
                    'up':1
                    ,'right':2
                    ,'down':3
                    ,'left':4
                }
                layer.tips(options.msg, options.selector,{
                    tips:[direct[options.direct]||2,options.backColor||'#393D49']
                    ,tipsMore: options.tipsMore||false
                });
            }
        }
        , closeLayer(index){
            index ? layer.close(index) : layer.closeAll();
        }
        //ajax
        , sendXHR(options,done,fail){
            let deffer = $.ajax($.extend({},{
                url:''
                ,type:'post'
                ,dataType:'json'
                ,data:null
                //,contentType:'application/json;charset=utf-8'
            },options));
            typeof done == 'function' && (
                deffer.then((resObj)=>{
                   done.call(null,resObj)
                },(resObj)=>{
                    if(!fail){
                        return common.msg.error("ajax请求失败！")
                    }
                    typeof fail == 'function' && fail.call(resObj)
                })
            )
            return deffer;
        }
        //重置表单
        , resetForm(formId){
            document.getElementById(formId).reset();
        }
        //获取表单数据
        ,getFormData(formId){
            return $("#"+formId).serializeArray();
        }
        //添加表单数据
        ,addFormItem(formData,name,value){
            formData.push({name:name,value:value})
            return formData;
        }
        //转json对象
        , serializeArrayToJson(serializeArray){
            let jsonObj = {}
            serializeArray.map(function(item){
                jsonObj[item.name+''] = item.value
            });
            return jsonObj;
        }
        //获取serialize值
        ,getSerializeVal(serializeArray,name){
            for(let i=0,len=serializeArray.length; i<len; i++){
                let item = serializeArray[i]
                if(item.name == name){
                    return {item:item,index:i};
                }
            }
        }
        /**
         * 渲染模板语法
         * tplEl:模板元素
         * pourEl注入元素
         * data:数据
         */
        , renderTpl(tplEl,pourEl,data,insertMethod){
            if(typeof data != 'object'){return}
            tplEl = typeof tplEl == 'string'? tplEl : tplEl.innerHTML
            laytpl(tplEl).render(data, function(html){
                if(!insertMethod){
                    pourEl.innerHTML = html;
                }else{
                   typeof insertMethod == 'function' && insertMethod.call(pourEl,html);
                }
            });
        }
        , addEvt(el,eventName,callback,useCapture=false){
            let isHasAddEvtLis = false;
            if(el){
                if(el.length && el.length > 0){
                    el[0].addEventListener && (isHasAddEvtLis = true)
                }else{
                    el.addEventListener && (isHasAddEvtLis = true)
                }
                if(isHasAddEvtLis) {
                    if(this.isDOMEl(el)){
                        el.addEventListener(eventName, callback, useCapture);
                    }else{
                        let elLen = el.length;
                        for(let i = 0; i < elLen; i++){
                            el[i].addEventListener(eventName, callback, useCapture);
                        }
                    }
                }
            }
        }
        , isVisible(el){
            let style= el.style;
            if(style.display == 'none'){
                return false
            }
            if(style.visibility == 'collapse'|| style.visibility == 'hidden'){
                return false;
            }
            if(!style.border){
                if(parseInt(this.css(el,'width')) ==0  || parseInt(this.css(el,'height')) == 0){
                    return false;
                }
            }
            //元素是否在屏幕窗口范围内
            let winClientWidth = document.documentElement.clientWidth;
            let winClientHeight = document.documentElement.clientHeight;
            let rect = this.offset(el);
            if(!(rect.l > 0 && rect.l < winClientWidth) || !(rect.t > 0 && rect.t < winClientHeight)){
                return false;
            }
            return true;
        }
        , isHasScrolled(ele,direction){
            ele = ele ? ele : document;
            if(direction==='y'){
                return ele.scrollHeight>ele.clientHeight;
            }else if(direction==='x'){
                return ele.scrollWidth>ele.clientWidth;
            }
        }
        , hide(el){
            let execBody = (el)=>{
                this.css(el,'display','none');
            }
            if(this.isDOMEl(el)){
                execBody(el)
            }else{
                this.arrayLike(el).forEach(ele=>{
                    execBody(ele);
                })
            }
        }
        , show(el){
            let execBody = (el)=>{
                this.css(el,'display','block');
            }
            if(this.isDOMEl(el)) {
                execBody(el)
            }else{
                this.arrayLike(el).forEach(ele=>{
                    execBody(ele);
                })
            }
        }
        , attr(el,htmlAttr,val){
            if(!val && typeof htmlAttr == 'string'){
                return el.getAttribute(htmlAttr)
            }
            if(!val && this.isPlainObject(htmlAttr)){
                for(let htmlKey in htmlAttr){
                    val = htmlAttr[htmlKey]
                    el.setAttribute(htmlKey,val)
                }
            }else {
                el.setAttribute(htmlAttr,val)
            }
        }
        , eventExtend(targetObj,eventName,callback){
            let oldEvent = targetObj[eventName];
            if(oldEvent == null){
                targetObj['on'+eventName] = callback;
            }else{
                targetObj['on'+eventName] = function () {
                    oldEvent();
                    callback();
                }
            }
        }
        //对象字面量判断
        , isPlainObject(obj){
            let flag = false;
            if(!obj || typeof obj != 'object'){return flag;}
            if(obj.constructor.prototype.hasOwnProperty("isPrototypeOf")){
                flag = true;
            }
            return flag;
        }
        //对象深拷贝
        , extend(){
            let args = this.arrayLike(arguments)
                , target = args.shift();
            args.forEach((arg)=>{
                let keys = Object.keys(arg);
                keys.forEach((key)=>{
                    let val = arg[key];
                    if(this.isPlainObject(val) || Array.isArray(val)){
                        let newTarget = Array.isArray(val)?[]:{};
                        //extend()返回给newTarget,再把newTarget值赋值给上一个目标对象 的key
                        !target[key] ? target[key] = this.extend(newTarget,val) : this.extend(target[key],val)
                    }else{
                        target[key] = val;
                    }
                });
            });
            return target;
        }
          //简单节点树，转为父子节点树
        , parentSubTree(nodes){
            let nodePoint = {},newNodes = [];
            nodes.forEach(node=>{
                node.children && delete node.children;
            });
            nodes.forEach(node=>{
                nodePoint[node.id] = node
            })
            nodes.forEach((node,i)=>{
                if(node.pid in nodePoint){//if(nodePoint[node.pid])
                    (nodePoint[node.pid].children || (nodePoint[node.pid].children = [])).push(node);
                }else{//不在则是顶级节点
                    newNodes.push(node);
                }
            });
            return newNodes;
        }
          //父子节点树转为简单节点树
        , parSubTransformSimple(nodes,childName){
            childName = childName || 'children'
            let _self = this, simpleNodes = [];
            for(let i = 0; i < nodes.length; i++){
                let node = nodes[i];
                node.pid = null;
                simpleNodes.push(node);
                getchildNode(node)
            }
            return simpleNodes;
            function getchildNode(node){
                let childNode = node[childName];
                childNode.pid = node.id;
                if(childNode){
                    simpleNodes = simpleNodes.concat(_self.parSubTransformSimple(childNode,childName));
                }
            }
        }
        //发布订阅模式
        , pubSubObj(){
            let _self = this , subEvents = _self.subEvents;
            //订阅方法subscribe 类似于on / watcher
            let subscribe = function(eventType,handle){
                    !(eventType in subEvents) && (subEvents[eventType] = [])
                    subEvents[eventType].push(handle);
                }
                //发布函数publish 类似于trigger / observe
                //data是数组
                , publish = function(eventType, data){
                    eventType = subEvents[eventType];
                    for (let i = 0; i < eventType.length; i++) {
                        eventType[i].apply(null, data);
                    }
                }
                //删除全部订阅
                , unSubscribe = function(eventType) {
                    subEvents[eventType] && delete subEvents[eventType]
                }
                //通过handle删除指定订阅
                , unSubscribeByFun = function(eventType,handle){
                    eventType = subEvents[eventType];
                    if (eventType) {
                        let handleIndex = eventType.indexOf(handle);
                        if (handleIndex >= 0) {
                            eventType.splice(handleIndex, 1);
                        }
                    }
                }
            return {
                subscribe,
                publish,
                unSubscribe,
                unSubscribeByFun
            };
        }
        /**
        * 异步渲染dom元素。
        * 支持同步渲染和异步渲染两种方式。异步渲染请指定url、同步渲染请指定data
        * options={
        *  url:'',可选项,url和data请确保其中任意一个有值
        *  dataFormat:可选项，使用时必须把格式化后的数据return
        *  tplEl:必选项,可以是模板元素本身或tplEL的id属性值
        *  mountEl:必选项,数据最终要渲染到那个容器中，可以是模板元素本身或tplEL的id属性值
        *  reload：可选项，是否可被重新加载，默认为false，不重新加载
        *  updateFormControlType:可选项,要更新的表单控件类型。'radio','checkbox','select','all'。若不指定默认是'all'
         * rendered:可选项，渲染完成后的回调
        * }
        * */
        , asyncRenderDOMEl(options){
            let setting = $.extend(true,{},{
                mountEl:''
                ,tplEl:''
                ,reload:false
                ,data:[]
                ,url:''
                ,reqParams: null
                ,updateFormControlType:''
                ,page:{
                    isEnable: false
                    ,elem:''
                    ,prop:{
                        pageNum:'page'
                        ,pageSize:'pageSize'
                        ,totalCount:'rowCount'
                    }
                    ,pageNum:1
                    ,pageSize:10
                    ,totalCount:1
                }
                ,insertMethod:null
                ,dataFormat:null
                ,rendered(data){}
                ,isFirstLoading:true//是否是首次加载
            },options)
            ,id = setting.mountEl
            ,page = setting.page
            ,mountEl = setting.mountEl
            ,tplEl = setting.tplEl
            ,url = setting.url
            ,dataFormat = setting.dataFormat
            ,renderDOMEl = function (tplEl,mountEl,data) {
                !setting.insertMethod && (mountEl.innerHTML = '')
                common.renderTpl(tplEl,mountEl,data,setting.insertMethod)
                //添加是否加载标识
                mountEl.setAttribute('isload',true)
                if(setting.updateFormControlType){
                    if(setting.updateFormControlType == 'all'){
                        form.render();
                    }else{
                        form.render(setting.updateFormControlType);
                    }
                }
                let dftData = Array.isArray(data)?data[0]: data[Object.keys(data)[0]]
                setting.rendered.call(mountEl,data,dftData);
            }
            ,pageHelper = function (page,totalCount) {
                if(page.isEnable && page.elem){
                    page.totalCount = totalCount;
                    laypage.render({
                        elem:page.elem
                        ,limit:page.pageSize
                        ,count:page.totalCount
                        ,jump: function(obj,first){
                            //first表示第一次加载
                            if(!first){
                                common.asyncRenderDOMEl($.extend(true,options,{
                                    page:{
                                        pageNum:obj.curr
                                    }
                                    ,isFirstLoading:false
                                }))
                            }
                        }
                    });
                }
            }
            ,reqParams = function (page,reqParams) {
                return page.isEnable? $.extend(reqParams,{
                    [page.prop.pageNum]:page.pageNum
                    ,[page.prop.pageSize]:page.pageSize
                }):reqParams;
            }(page,setting.reqParams);
            mountEl = !common.isDOMEl(mountEl) ? common.getEl(mountEl):mountEl;
            tplEl = !common.isDOMEl(tplEl) ? common.getEl(tplEl):tplEl;
            //如果控制不能重复加载并且已经加载了，则不做任何处理
            if(mountEl.getAttribute('isload') && !setting.reload){return;}
            //如果reload为true则重新加载
            if(mountEl && url || (mountEl && url && setting.reload)){
                common.sendXHR({
                    url:url
                    ,data:reqParams||null
                },(resObj)=>{
                    if(dataFormat){
                        let dataFormats = dataFormat.call(null,resObj);
                        if(dataFormats){
                            renderDOMEl(tplEl,mountEl,dataFormats);
                        }
                    }else{
                        renderDOMEl(tplEl,mountEl,resObj);
                    }
                    setting.isFirstLoading && pageHelper(page,resObj[page.prop.totalCount]||1);
                },(resObj)=>{console.log(options.url+"请求失败！")});
            }else{
                if(!url && Array.isArray(setting.data)){
                    if(dataFormat){
                        let dataFormats = dataFormat.call(null,setting.data);
                        renderDOMEl(tplEl,mountEl,dataFormats);
                    }else{
                        renderDOMEl(tplEl,mountEl,setting.data);
                    }
                    setting.isFirstLoading && pageHelper(page,setting.data.length||1);
                }
            }
            //保存配置
            common.renderDOMElOption[id] = setting;
        }

        , reloadRenderDOMEl(mountId,options){
            common.asyncRenderDOMEl($.extend(true,common.renderDOMElOption[mountId],options))
        }
        /**
         * 创建弹窗
         * */
        , createLayer(options){
            layer.open($.extend({},{
                type: 1
                , area: 'auto'
                , offset: 'auto'
                , fixed: true
                //,move: false  //禁止拖拽
                , scrollbar: false //禁用窗口滚动条
                , title: ''
                , btn: ["确定","取消"]
                , btnAlign: 'c'
                , content: ''
                , success: function(layero, index) {

                }
                //确定按钮的回调
                ,yes: function(index, layero){

                }
                //取消按钮的回调
                ,btn2:function (index, layero) {
                    layer.close(index)
                }
                //'×'符号的回调
                ,cancel:function (index,layero) {
                    layer.close(index)
                }
            },options));
        }
        /**
         * 添加表行
         * */
        ,addRow(tableId,data) {
            let rowsData = table.cache[tableId];
            rowsData.unshift(data);
            this.reRenderTable(tableId,{
                data:rowsData
                ,url:""
            });
        }
        /**
         * tableIns:必须项
         * where:必须是一个对象字面，可选项
         * curTablePage:数值类型，可选项
         * */
        , reloadTable(tableIns,curTablePage,where){
            typeof curTablePage == 'object' && (
                where = curTablePage,
                curTablePage = 1
            )
            tableIns.reload({
                where:where
                ,page:{
                    curr: curTablePage||1
                }
            });
        }
        /**
         * 重新渲染表格
         */
        , reRenderTable(tableId,options){
            this.initTable($.extend({},this.tablesOption[tableId],options||{}));
        }
        /**
         * 初始化表格
         * */
        , initTable(options){
            options = $.extend({},{
                elem: ''
                ,height: 'auto'//full-333
                ,method: 'post'
                ,url: '' //数据接口
                ,page: true //开启分页
                ,parseData: function(res){ //res 即为原始返回的数据
                    return {
                        "status": '200', //解析接口状态
                        "message": 'success', //解析提示文本
                        "pageSize":res.pageSize||10,//页大小
                        "totalCount": res.rowCount||res.length, //总页数
                        "data": res.data||res //解析数据列表
                    };
                }
                ,cols: null
                ,done:function(res, curr, count){
                    //如果是异步请求数据方式，res即为你接口返回的信息。
                    //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                }
            },options)
            //表格Id为key
            this.tablesOption[options.elem.split("#")[1]] = options;
            let tableIns = table.render(options);
            return tableIns;
        }
        /**
         * 监听行工具条
         * */
        , toolBarEvtListener(tableId,callback){
            table.on('tool('+tableId+')', function(rowObj){
                callback.call(this,rowObj)
            });
        }
        /**
         * 监听头工具条
         * */
        ,toolHeadEvtListener(tableId,callback){
            //头工具栏事件
            table.on('toolbar('+tableId+')', function(obj){
                callback.call(this,obj)
            });
        }
        /**
         * 监听表格单选
         * */
        ,listenerTableRadio(tableId,callback){
            table.on('radio('+tableId+')',function(obj){
                typeof callback == 'function' && callback.call(this,obj);
            })
        }
        /**
         * 监听表格复选框
         * */
        ,listenerTableCheckbox(tableId,callback){
            table.on('checkbox('+tableId+')', function(obj){
                callback.call(this,obj)
            });
        }
        /**
         * 获取表格缓存数据
         * */
        ,getTableCache(tableId){
            return table.cache[tableId]
        }
        /**
         * 监听选项卡切换
         * */
        ,listenerTabCar(filterId,callback){
            element.on('tab('+filterId+')', function(data){
                typeof callback == 'function' && callback.call(this,data);
            });
        }
        /**
         * 获取选中的表格数据
         * tableId不要带#号
         * */
        , getCheckedData(tableId,noTip){
            let checkStatus = table.checkStatus(tableId)
                ,checkData = checkStatus.data;
            if(checkData.length<=0 && !noTip){common.msg.warn("请至少选中一行！！");return;}
            return checkData;
        }
        /**
         *  初始化日期
         *  mountEl：挂在点
         *  doned：选择完毕后的回掉函数
         *  initVal:默认日期值 接收这种格式yyyy-MM-dd或者是一个Date对象
         */
        , initCalender(options){
            return laydate.render($.extend({},{
                elem: '' //指定元素
                ,value:''
                ,type:'date'
                ,format:'yyyy-MM-dd'
                ,btns:['clear', 'now', 'confirm']
                ,done: function(value,data){
                    $(this.elem).val(value)
                }
            },options));
        }
        ,initUploadFile(options, $img){
            return upload.render($.extend({}, {
                elem: '#up-depart-img-btn' //绑定元素
                //默认就是图片类型
                , exts: 'jpg|png|gif|jpeg'
                , url: '' //上传接口
                , size: 1024*200
                , field: 'imgData'
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    // obj.preview(function (index, file, result) {
                    //     $img.show().attr('src', result);
                    // });
                }
                , done: function (res,index,upload) {
                    //上传完毕回调
                    $img.attr('src', res.url); //图片链接（base64）
                }
                , error: function () {
                    //请求异常回调
                    common.msg.error("上传失败！")
                }
            }, options));
        }
        ,resetFileUp(upBtnId){
            $(upBtnId).data('haveEvents', null);
        }
        ,render(moduleName,object,layFilter){
            if(!deps[moduleName]){return console.error(moduleName+'未定义！');}
           return deps[moduleName].render(object,layFilter||'');
        }
        ,contains(moutEl,targetEl){
            let moutEls = Array.from(document.querySelectorAll(moutEl));
            for(let i = 0,len = moutEls.length; i < len; i++){
                moutEl = moutEls[i]
                if(moutEl.contains(targetEl)){
                    return true;
                }
            }
            return false;
        }
        ,pageHelper(options){
            return laypage.render($.extend({},{
                elem: ''
                ,count: 1
                ,limit:10
                ,jump: function(obj,first){
                    //first表示是否是第一次加载
                    if(!first){

                    }
                }
            },options));
        }
    }

    let common = new Common();

    exports(MOD_NAME, common);
})